//
//  CommonService.m
//  DYS
//
//  Created by 房 国生 on 15/6/19.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "CommonService.h"
#import "AFNetworking.h"
#import "AdEntity.h"
#import "DBManager.h"
#import "AppDelegate.h"
#import "SpotEntity.h"
#import "RoadLineEntity.h"

//ShareSDK必要头文件
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApi.h"

//新浪微博SDK头文件
#import "WeiboSDK.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKExtension/SSEShareHelper.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetStyle.h>

#import "DPConstants.h"
#import "Reachability.H"
#import "TopBannerEntity.h"
#import "LPUtils.h"
#import "LoginViewController.h"
@implementation CommonService

- (void)getNetWorkData:(NSDictionary *)param
                  Path:(NSString *)path
             Successed:(void(^)(id entity)) successed
                Failed:(void(^)(NSInteger errorCode ,NSString *message))failed
{
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[[NSURL alloc] initWithString:BASEURL]];
    [client registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    NSString *timeInterval = [NSString stringWithFormat:@"%ld",time(NULL)];
    NSString *apiVersion = API_VERSION;
    NSString *phoneClass = PhoneClass;
    NSString *version = Secert_VERSION;
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:timeInterval,@"Reqtime",apiVersion,@"Apiversion",phoneClass,@"Phoneclass",version,@"Version", nil];
    if ([UserEntity sharedInstance].session_id) {
        [dictionary setObject:[UserEntity sharedInstance].session_id forKey:@"Sessionid"];
    }
    else
    {
        [dictionary setObject:@"" forKey:@"Sessionid"];

    }
    [dictionary setObject:@"" forKey:@"Appid"];

    NSMutableDictionary *muDicParm = [[NSMutableDictionary alloc]initWithDictionary:param];
    [muDicParm enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSString *encodedString = (NSString *)
        CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                  (CFStringRef)obj,
                                                                  NULL,
                                                                  (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                  kCFStringEncodingUTF8));
        [muDicParm setObject:encodedString forKey:key];
    }];
    [dictionary addEntriesFromDictionary:muDicParm];
    NSMutableString *jsonString = [self toString:dictionary];
    [jsonString appendString:SignKEY];
    NSString *signString = [LPUtils CCSMD5:[LPUtils CCSMD5:[NSString stringWithFormat:@"%@",jsonString]]];
    [client setDefaultHeader:@"Sign" value:signString];
    [client setDefaultHeader:@"Reqtime" value:timeInterval];
    [client setDefaultHeader:@"Apiversion" value:apiVersion];
    [client setDefaultHeader:@"Phoneclass" value:phoneClass];
    [client setDefaultHeader:@"Version" value:version];
    [client setDefaultHeader:@"Appid" value:@""];
    if ([UserEntity sharedInstance].session_id) {
        [client setDefaultHeader:@"Sessionid" value:[UserEntity sharedInstance].session_id];
    }
    else
    {
        [client setDefaultHeader:@"Sessionid" value:@""];
    }
    
    
    client.parameterEncoding = AFFormURLParameterEncoding;
    [client postPath:path parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        DebugLog(@"%@", result);
        
        NSError *e;
        NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&e];
        NSNumber *code = [resultDictionary objectForKey:@"code"];
        if ([code intValue] == -12) {
            LoginViewController *mvc = [[LoginViewController alloc]init];
            UITabBarController *tab = (UITabBarController*) [AppDelegate instance].window.rootViewController;
            UINavigationController *nav =  (UINavigationController*)[tab.viewControllers lastObject];
            [nav pushViewController:mvc animated:YES];
        }

        if (resultDictionary == nil) {
            failed(1,result);
        }
        else {
            successed(resultDictionary);
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSInteger errorCode = error.code;
        NSString *errorMessage = [error localizedDescription];
        
        failed(errorCode,errorMessage);
    }];
//    [client getPath:path
//          parameters:param
//             success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            
//                     NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//                     DebugLog(@"%@", result);
//                     
//                     NSError *e;
//                     NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&e];
//                     
//                     if (resultDictionary == nil) {
//                         failed(1,result);
//                     }
//                     else {
//                         successed(resultDictionary);
//                     }
//
//                 
//                 
//             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                 NSInteger errorCode = error.code;
//                 NSString *errorMessage = [error localizedDescription];
//                 
//                 failed(errorCode,errorMessage);
//             }];
}


- (NSMutableString *)toString:(NSDictionary *)dictModel
{
    NSMutableString *string = [[NSMutableString alloc]init];
    NSArray* arr = [dictModel allKeys];
    arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        NSComparisonResult result = [obj1 compare:obj2];
        return result==NSOrderedDescending;
    }];
    
    for (NSString *subString in arr)
    {
        [string appendString:subString];
        [string appendString:@"="];
        [string appendString:[dictModel objectForKey:subString]];
        if (![subString isEqualToString:[arr lastObject]]) {
            [string appendString:@"&"];
        }
    }
    return string;
    
//    if ([NSJSONSerialization isValidJSONObject:dictModel])
//    {
//        
//        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dictModel options:NSJSONWritingPrettyPrinted error:nil];
//        NSString * jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
//        return jsonStr;
//    }
//    return nil;
}

- (void)getDianPingData:(NSDictionary *)param
                   Path:(NSString *)path
              Successed:(void(^)(id entity)) successed
                 Failed:(void(^)(NSInteger errorCode ,NSString *message))failed {
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[[NSURL alloc] initWithString:kDPAPIDomain]];
    [client registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    client.parameterEncoding = AFFormURLParameterEncoding;
    [client getPath:path
          parameters:param
             success:^(AFHTTPRequestOperation *operation, id responseObject) {
                 NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                 DebugLog(@"%@", result);
                 
                 NSError *e;
                 NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&e];
                 
                 if (resultDictionary == nil) {
                     successed(result);
                 }
                 else {
                     successed(resultDictionary);
                 }
                 
             } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 NSInteger errorCode = error.code;
                 NSString *errorMessage = [error localizedDescription];
                 
                 failed(errorCode,errorMessage);
             }];
}
/**
 * 下载文件
 */
- (void)downloadFileURL:(NSString *)aUrl
               SavePath:(NSString *)aSavePath
               FileName:(NSString *)aFileName
                    Tag:(NSInteger)aTag
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //检查本地文件是否已存在
    NSString *fileName = [NSString stringWithFormat:@"%@/%@", aSavePath, aFileName];
    //检查附件是否存在
    if ([fileManager fileExistsAtPath:fileName]) {
        //NSData *audioData = [NSData dataWithContentsOfFile:fileName];
        //[self requestFinished:[NSDictionary dictionaryWithObject:audioData forKey:@"res"] tag:aTag];
    }
    else{
        //创建附件存储目录
        if (![fileManager fileExistsAtPath:aSavePath]) {
            [fileManager createDirectoryAtPath:aSavePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        //下载附件
        NSURL *url = [[NSURL alloc] initWithString:aUrl];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.inputStream   = [NSInputStream inputStreamWithURL:url];
        operation.outputStream  = [NSOutputStream outputStreamToFileAtPath:fileName append:NO];
        
        //下载进度控制
        [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
             NSLog(@"is download：%f", (float)totalBytesRead/totalBytesExpectedToRead);
             [_delegate getDownloadProgress:(float)totalBytesRead/totalBytesExpectedToRead];
         }];
        
        //已完成下载
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            //NSData *audioData = [NSData dataWithContentsOfFile:fileName];
            //设置下载数据到res字典对象中并用代理返回下载数据NSData
            //[self requestFinished:[NSDictionary dictionaryWithObject:audioData forKey:@"res"] tag:aTag];
            [_delegate finishDownload:YES];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //下载失败
            //[self requestFailed:aTag];
            [_delegate finishDownload:NO];
        }];
        
        [operation start];
    }
}

- (void)getHomeAdImage:(NSDictionary *)param
             Successed:(void(^)(NSArray *arrayHomeImage)) successed
                Failed:(void(^)(NSInteger errorCode ,NSString *message))failed
{
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[[NSURL alloc] initWithString:BASEURL]];
    [client registerHTTPOperationClass:[AFHTTPRequestOperation class]];
    NSString *timeInterval = [NSString stringWithFormat:@"%ld",time(NULL)];
    NSString *apiVersion = API_VERSION;
    NSString *phoneClass = PhoneClass;
    NSString *version = Secert_VERSION;
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]initWithObjectsAndKeys:timeInterval,@"Reqtime",apiVersion,@"Apiversion",phoneClass,@"Phoneclass",version,@"Version", nil];
    if ([UserEntity sharedInstance].session_id) {
        [dictionary setObject:[UserEntity sharedInstance].session_id forKey:@"Sessionid"];
    }
    else
    {
        [dictionary setObject:@"" forKey:@"Sessionid"];
        
    }
    [dictionary addEntriesFromDictionary:param];
    NSMutableString *jsonString = [self toString:dictionary];
    [jsonString appendString:SignKEY];
    NSString *signString = [LPUtils CCSMD5:[LPUtils CCSMD5:[NSString stringWithFormat:@"%@",jsonString]]];
    [client setDefaultHeader:@"Sign" value:signString];
    [client setDefaultHeader:@"Reqtime" value:timeInterval];
    [client setDefaultHeader:@"Apiversion" value:apiVersion];
    [client setDefaultHeader:@"Phoneclass" value:phoneClass];
    [client setDefaultHeader:@"Version" value:version];
    if ([UserEntity sharedInstance].session_id) {
        [client setDefaultHeader:@"Sessionid" value:[UserEntity sharedInstance].session_id];
    }
    else
    {
        [client setDefaultHeader:@"Sessionid" value:@""];
    }
    
    
    client.parameterEncoding = AFFormURLParameterEncoding;
    [client postPath:PATH parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
                //NSDictionary *resultDictionary = responseObject;
                NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"%@", result);
                
                NSError *e;
                NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&e];
                
                if (!resultDictionary) {
                    
                }
                else
                {
                    NSMutableArray *array = [resultDictionary objectForKey:@"content"];
                    NSMutableArray *arrayHomeImageEntity = [[NSMutableArray alloc] init];
                    for (NSDictionary* attributes in array) {
                        AdEntity *entity = [[AdEntity alloc] init];
                        entity = [entity initWithAttributes:attributes];
                        [arrayHomeImageEntity addObject:entity];
                    }
                    
                    successed(arrayHomeImageEntity);
                }
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSInteger errorCode = error.code;
                NSString *errorMessage = [error localizedDescription];
                
                failed(errorCode,errorMessage);
            }];
}

/**
 *  上传图片
 */
+ (NSDictionary *) uploadUserImage:(UserEntity *)user FileName:(NSString *)fileName Image:(NSData *)imageData {
    
    NSString *url = [NSString stringWithFormat:@"%@/User/upload_image", BASEURL];
    
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    
    NSString *lineEnd = @"\r\n";
    NSString *twoHyphens = @"--";
    NSString *boundary = @"------------------------7dc2fd5c0894";
    
    NSMutableString *mString = [[NSMutableString alloc] init];
    [mString appendString:twoHyphens];
    [mString appendString:boundary];
    [mString appendString:lineEnd];
    [mString appendString:@"Content-Disposition: form-data; name=\"uid\"\r\n\r\n"];
    [mString appendString:user.userId];
    [mString appendString:lineEnd];
    [mString appendString:twoHyphens];
    [mString appendString:boundary];
    [mString appendString:lineEnd];
    [mString appendFormat:@"Content-Disposition: form-data; name=\"Filedata\";filename=\"%@.jpg\"%@",fileName,lineEnd];
    [mString appendString:@"Content-Type:image/jpeg"];
    [mString appendString:lineEnd];
    [mString appendString:lineEnd];
    
    NSString *body = [NSString stringWithString:mString ];
    
    NSString *end = [NSString stringWithFormat:@"%@%@%@%@%@",lineEnd,twoHyphens,boundary,twoHyphens,lineEnd];
    
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:imageData];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",boundary];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    [request setValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];
    
    NSError *error = nil;
    NSURLResponse *theResponse = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error];
    NSError *e;
    NSString *strRes = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
    
    DebugLog(@"%@", strRes);
    
    if (data != nil) {
        NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&e];
        return resultDictionary;
    }
    else {
        return nil;
    }
    //return [[resultDictionary objectForKey:@"result"] boolValue];
}

+ (NSDictionary *)uploadUserYJ:(NSDictionary *)dicYJ FileName:(NSMutableArray *)fileName Image:(NSMutableArray *)imageData {
    //NSString *url = @"http://112.4.89.82/dev/zycmm/upload.php";
    
    NSString *url = [NSString stringWithFormat:@"%@/user_travel/save", BASEURL];
    
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    
    NSString *lineEnd = @"\r\n";
    NSString *twoHyphens = @"--";
    NSString *boundary = @"------------------------7dc2fd5c0894";
    
/*
 @"1", @"userid",
 @"20", @"content",
 @"20", @"parkid",
 @"20", @"longitude",
 @"20", @"latitude",
 @"20", @"roadname",nil];
 */
    NSMutableString *mString = [[NSMutableString alloc] init];
    NSArray *keys= [dicYJ allKeys];
    for(int i=0;i<[keys count];i++) {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        [mString appendString:twoHyphens];
        [mString appendString:boundary];
        [mString appendString:lineEnd];
        [mString appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        [mString appendString:[dicYJ valueForKeyPath:key]];
        [mString appendString:lineEnd];
    }

    
    NSString *body = [NSString stringWithString:mString ];
    
    NSString *end = [NSString stringWithFormat:@"%@%@%@%@%@",lineEnd,twoHyphens,boundary,twoHyphens,lineEnd];
    
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    for (int i = 0; i < [fileName count]; i++)
    {
        //得到图片的data
        NSData* data = [imageData objectAtIndex:i];
        NSMutableString *imgbody = [[NSMutableString alloc] init];
        //添加分界线，换行
        [imgbody appendString:twoHyphens];
        [imgbody appendString:boundary];
        [imgbody appendString:lineEnd];
        [imgbody appendFormat:@"Content-Disposition: form-data; name=\"Filedata%d\";filename=\"%@.jpg\"%@",i+1,[fileName objectAtIndex:i],lineEnd];
        //声明上传文件的格式
//        [imgbody appendString:@"Content-Type:image/jpeg"];
        [imgbody appendFormat:@"Content-Type:image/jpeg\r\n\r\n"];

//        NSLog(@"上传的图片：%d  %@", i, [keys objectAtIndex:i]);
        
        //将body字符串转化为UTF8格式的二进制
        [myRequestData appendData:[imgbody dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [myRequestData appendData:data];
        [myRequestData appendData:[ @"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",boundary];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    [request setValue:@"Keep-Alive" forHTTPHeaderField:@"Connection"];
    
    NSError *error = nil;
    NSURLResponse *theResponse = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&error];
    NSError *e;
    
    if (data == nil) {
        return nil;
    }
    else {
        NSString *strRes = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
        DebugLog(@"%@", strRes);
        NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&e];
        
        return resultDictionary;
    }
}

/***
 * 此函数用来判断是否网络连接服务器正常
 * 需要导入Reachability类
 */
+ (BOOL)isExistenceLETFINetwork:(NSString *)url
{
    BOOL isExistenceNetwork = NO;
    Reachability *reachability = [Reachability reachabilityWithHostName:LET_FI];  // 测试服务器状态
    
    switch([reachability currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = FALSE;
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = TRUE;
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = TRUE;
            break;
    }
    
    if (isExistenceNetwork) {
        
        NSMutableURLRequest *fileRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                                   cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                               timeoutInterval:3.0];
        
        if (fileRequest == nil) {
            return NO;
        }
        else {
            return YES;
        }
    }
    else {
        return isExistenceNetwork;
    }
}

/**
 *  获取本地数据
 */
- (BOOL) getSpotDataFromLocal:(NSString *)parkId
                       CityId:(NSString *)cityId
                    ArraySpot:(NSMutableArray *)arraySpot
                ArrayBusiness:(NSMutableArray *)arrayBusiness
                  ArrayToilet:(NSMutableArray *)arrayToilet
                  ArrayRoadLine:(NSMutableArray *)arrayRoadLine
                   ParkEntity:(ParkEntity *)parkEntity
                ArrayBusinessTogether:(NSMutableArray *)arrayBusinessTogether
                        Array:(NSMutableArray *)arrayTogether
                 TopBannerArr:(NSMutableArray *)topBannerArr
                  ActivityArr:(NSMutableArray *)activityArr
{
    ParkEntity *entity = [DBManager selectParkByParkId:parkId];
    //read data from the json file
    if (entity != nil) {
        [arraySpot removeAllObjects];
        [self readFile:@"attraction_json" ParkId:parkId Array:arraySpot];
        [self readFile:@"business_json" ParkId:parkId Array:arrayBusiness];
        //[self readFile:@"park_json" ParkId:parkId];
        [self readFile:@"toilet_json" ParkId:parkId Array:arrayToilet];
        [self readFile:@"roadline_json" ParkId:parkId Array:arrayRoadLine];
        [self readFile:@"top_banner_json" ParkId:parkId Array:topBannerArr];
        [self readFile:@"activity_json" ParkId:parkId Array:activityArr];
        for (int k = 1; k < 6; k ++) {
            NSMutableArray *array1 = [NSMutableArray array];
            NSString *str = [NSString stringWithFormat:@"business_2.%d_list",k];
            [self readFile:str ParkId:parkId Array:array1];
            [arrayBusinessTogether addObject:array1];

        }
        for (int i = 5; i < 16; i ++) {
            NSMutableArray *array1 = [NSMutableArray array];
            NSString *str = [NSString stringWithFormat:@"attraction_%d_list",i];
            [self readFile:str ParkId:parkId Array:array1];
            [arrayTogether addObject:array1];
        }

        NSMutableArray *arrayPark = [[NSMutableArray alloc] init];
        [self readFile:@"park_json" ParkId:parkId Array:arrayPark];
        if ([arrayPark count] > 0) {
            ParkEntity *park = [arrayPark objectAtIndex:0];
            parkEntity.latitude = park.latitude;
            parkEntity.longitude = park.longitude;
            parkEntity.map_width = park.map_width;
            parkEntity.map_height = park.map_height;
            parkEntity.ticket_url = park.ticket_url;
            parkEntity.radius = park.radius;
            parkEntity.city_id = cityId;
            parkEntity.questionnaire_url = park.questionnaire_url;
            parkEntity.source_version = park.source_version;
            parkEntity.activity_rows = park.activity_rows;
            parkEntity.title = park.title;
            parkEntity.park_rows = park.park_rows;
            parkEntity.notice_rows = park.notice_rows;
            [DBManager saveOrUpdataParkEntity:parkEntity];
        }
        
        [AppDelegate instance].file_from_local = YES;
    } else {
        [AppDelegate instance].file_from_local = NO;
        return NO;
    }
    
    return YES;
}

- (BOOL) getSpotLocalData:(NSString *)parkId
                ArraySpot:(NSMutableArray *)arraySpot
{
    ParkEntity *entity = [DBManager selectParkByParkId:parkId];
    //read data from the json file
    if (entity != nil) {
        [self readFile:@"attraction_json" ParkId:parkId Array:arraySpot];
       
//        NSMutableArray *arrayPark = [[NSMutableArray alloc] init];
//        [self readFile:@"park_json" ParkId:parkId Array:arrayPark];
//        if ([arrayPark count] > 0) {
//            ParkEntity *park = [arrayPark objectAtIndex:0];
//            
//        }
        
        [AppDelegate instance].spot_from_local = YES;
    }
    else {
        [AppDelegate instance].spot_from_local = NO;
        return NO;
    }
    return YES;
}

- (void) readFile:(NSString *) fileName ParkId:(NSString *)parkId Array:(NSMutableArray *)array {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *parkFoldName = [NSString stringWithFormat:@"park_%@",parkId ];
    NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
    NSString *path =[ NSString stringWithFormat:@"%@/%@", folder, parkFoldName ];
    NSString *json = [NSString stringWithFormat:@"%@/%@.txt", path, fileName];
    
    if ([fileManager fileExistsAtPath:json]) {
        //读取数据
        NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath:json];
        NSData *data = [file readDataToEndOfFile];//得到xml文件                               //读取到NSDate中
        
        NSString *aStr;
        aStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];         //转换为NSString
//        NSLog( @"aStr is %@", aStr );
        
        NSError *error = nil;
        NSArray *string2dic = [NSJSONSerialization JSONObjectWithData: data
                                                                   options: NSJSONReadingMutableContainers
                                                                     error: &error];
        // insert code here...
        NSLog(@"Hello, World!");
        
        if ([fileName isEqualToString:@"park_json"] == YES) {
            ParkEntity *entity = [[ParkEntity alloc] init];
            entity = [entity initWithAttributes:(NSDictionary* )string2dic];
            [array  addObject:entity];
        }
        else {
            //NSArray *array = (NSArray *)aStr;
            for (NSDictionary* attributes in string2dic) {
                
                if ([fileName isEqualToString:@"roadline_json"] == YES) {
                    RoadLineEntity *entity = [[RoadLineEntity alloc] init];
                    entity = [entity initWithAttributes:attributes];
                    [array  addObject:entity];
                }
                else if ([fileName isEqualToString:@"top_banner_json"]) {
                    TopBannerEntity *entity = [[TopBannerEntity alloc]initWithDict:attributes andParkId:parkId];
                    [array addObject:entity];
                }
                else if ([fileName isEqualToString:@"activity_json"]) {
                    [array addObject:attributes];
                }
                else {
                    SpotEntity *entity = [[SpotEntity alloc] init];
                    entity = [entity initWithAttributes:attributes];
                    [array  addObject:entity];
                }
            }
        }
        //
        [file closeFile];
    }
}

+ (NSString *) addLocalRootPath:(NSString *)url ParkId:(NSString *)parkId {
    
    NSRange range = [url rangeOfString:IMAGE_URL];
    //int location = range.location;
    //NSString *astring = [[NSString alloc] initWithString:[NSString stringWithFormat:@"Location:%i,Leight:%i",location,leight]];
    //NSLog(@"astring:%@",astring);
    
    /*----------------抽取子串 ----------------*/
    //-substringToIndex: 从+++++++++++++++++串的开头一直截取到指定的位置，但不包括该位置的字符
    NSString *string2 = [url substringFromIndex:range.length];
    NSLog(@"string2:%@",string2);
    
    NSString *localRootPath = [CommonService getLocalRootPath:parkId];
    NSString *localPath = [NSString stringWithFormat:@"%@%@", localRootPath, string2 ];
    
    return localPath;
}

+ (NSString *) getLocalRootPath:(NSString *)parkId {
    NSString *parkFoldName = [NSString stringWithFormat:@"park_%@",parkId ];
    
    NSString *document = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
    NSString *folder = [document stringByAppendingPathComponent:@"lyss"];
    NSString *path =[ NSString stringWithFormat:@"%@/%@", folder, parkFoldName ];
    
    return path;
}

+ (BOOL) deleteFile:(NSString *)filePath {
    NSFileManager* manager = [NSFileManager defaultManager];
    NSError *error;
    
    if ([manager fileExistsAtPath:filePath]) {
        if ([manager removeItemAtPath:filePath error:&error] != YES) {
            return NO;
        } else {
            return YES;
        }
    } else {
        return NO;
    }
}

//遍历文件夹获得文件夹大小，返回多少M
+ (NSString *)getFolderSize:(NSString *)parkId {
    
    NSString *folder_path = [CommonService getLocalRootPath:parkId];
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folder_path]) return @"0";
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folder_path] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folder_path stringByAppendingPathComponent:fileName];
        folderSize += [CommonService fileSizeAtPath:fileAbsolutePath];
    }
    NSString *strSize = [NSString stringWithFormat:@"%.1fM", folderSize/(1024.0*1024.0)];
    return strSize;
}

//单个文件的大小
+ (long long) fileSizeAtPath:(NSString*) filePath {
    
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//-----------------------------------------------------------------------------------------------------------------------
+ (void)initShareSDK {
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个参数用于指定要使用哪些社交平台，以数组形式传入。第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerApp:@"19761f53e09a4"
          activePlatforms:@[
                            @(SSDKPlatformTypeSinaWeibo),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ)]
                 onImport:^(SSDKPlatformType platformType) {
                     
                     switch (platformType)
                     {
                         case SSDKPlatformTypeWechat:
                             [ShareSDKConnector connectWeChat:[WXApi class]];
                             break;
                         case SSDKPlatformTypeQQ:
                             [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                             break;
                         default:
                             break;
                     }
                     
                 }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo) {
              
              switch (platformType)
              {
                  case SSDKPlatformTypeSinaWeibo:
                      //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                      [appInfo SSDKSetupSinaWeiboByAppKey:@"2901103274"
                                                appSecret:@"434be334ddfc7a6ecceedec49de8e3b2"
                                              redirectUri:@"http://www.leyouss.com/lyss"
                                                 authType:SSDKAuthTypeBoth];
                      break;
//                  case SSDKPlatformTypeTencentWeibo:
//                      //设置腾讯微博应用信息，其中authType设置为只用Web形式授权
//                      [appInfo SSDKSetupTencentWeiboByAppKey:@"801307650"
//                                                   appSecret:@"ae36f4ee3946e1cbb98d6965b0b2ff5c"
//                                                 redirectUri:@"http://www.sharesdk.cn"];
//                      break;
//                  case SSDKPlatformTypeFacebook:
//                      //设置Facebook应用信息，其中authType设置为只用SSO形式授权
//                      [appInfo SSDKSetupFacebookByAppKey:@"107704292745179"
//                                               appSecret:@"38053202e1a5fe26c80c753071f0b573"
//                                                authType:SSDKAuthTypeBoth];
//                      break;
//                  case SSDKPlatformTypeTwitter:
//                      [appInfo SSDKSetupTwitterByConsumerKey:@"LRBM0H75rWrU9gNHvlEAA2aOy"
//                                              consumerSecret:@"gbeWsZvA9ELJSdoBzJ5oLKX0TU09UOwrzdGfo9Tg7DjyGuMe8G"
//                                                 redirectUri:@"http://mob.com"];
//                      break;
                  case SSDKPlatformTypeWechat:
                      [appInfo SSDKSetupWeChatByAppId:@"wxe8f31d9530798638"
                                            appSecret:@"af42a1419240a9be1d7ff916906ad9c4"];
                      break;
                  case SSDKPlatformTypeQQ:
                      [appInfo SSDKSetupQQByAppId:@"1104694257"
                                           appKey:@"xclUnc0sB7WgHEin"
                                         authType:SSDKAuthTypeBoth];
                      break;
//                  case SSDKPlatformTypeDouBan:
//                      [appInfo SSDKSetupDouBanByApiKey:@"02e2cbe5ca06de5908a863b15e149b0b"
//                                                secret:@"9f1e7b4f71304f2f"
//                                           redirectUri:@"http://www.sharesdk.cn"];
                      break;
                  default:
                      break;
              }
              
          }];
}


#pragma mark 显示分享菜单

/**
 *  显示分享菜单
 *
 *  @param view 容器视图
 */
+ (void)showShareActionSheet:(UIView *)view
                         HUD:(MBProgressHUD *)hud
                  ImageArray:(NSArray* )imageArray
                         URL:(NSString *)url
                       Title:(NSString *)title
                     Content:(NSString *)content
{
    /**
     * 在简单分享中，只要设置共有分享参数即可分享到任意的社交平台
     **/
    //__weak ViewController *theController = self;
    //1、创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    NSString *short_content = @"";
    if (content.length > 30) {
        short_content = [NSString stringWithFormat:@"%@...", [content substringToIndex:30]];
    } else {
        short_content = content;
    }
    if (imageArray) {
        
        [shareParams SSDKSetupShareParamsByText:short_content
                                         images:imageArray
                                            url:[NSURL URLWithString:url]
                                          title:title
                                           type:SSDKContentTypeAuto];
        //设置分享编辑页面样式（optional）
        //        [SSUIShareActionSheetStyle setActionSheetBackgroundColor:[UIColor colorWithRed:249/255.0 green:0/255.0 blue:12/255.0 alpha:0.5]];
        //        [SSUIShareActionSheetStyle setActionSheetColor:[UIColor colorWithRed:21.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0]];
        //        [SSUIShareActionSheetStyle setCancelButtonBackgroundColor:[UIColor colorWithRed:21.0/255.0 green:21.0/255.0 blue:21.0/255.0 alpha:1.0]];
        //        [SSUIShareActionSheetStyle setCancelButtonLabelColor:[UIColor whiteColor]];
        //        [SSUIShareActionSheetStyle setItemNameColor:[UIColor whiteColor]];
        //        [SSUIShareActionSheetStyle setItemNameFont:[UIFont systemFontOfSize:10]];
        //        [SSUIShareActionSheetStyle setCurrentPageIndicatorTintColor:[UIColor colorWithRed:156/255.0 green:156/255.0 blue:156/255.0 alpha:1.0]];
        //        [SSUIShareActionSheetStyle setPageIndicatorTintColor:[UIColor colorWithRed:62/255.0 green:62/255.0 blue:62/255.0 alpha:1.0]];
        
        //2、分享
        [ShareSDK showShareActionSheet:view
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       NSLog(@"122");
                       switch (state) {
                               
                           case SSDKResponseStateBegin:
                           {
                               //[theController showLoadingView:YES];
                               [hud show:YES];
                               break;
                           }
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               [hud hide:YES];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               [hud hide:YES];
                               if (platformType == SSDKPlatformTypeSMS && [error code] == 201)
                               {
                                   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                                   message:@"失败原因可能是：1、短信应用没有设置帐号；2、设备不支持短信应用；3、短信应用在iOS 7以上才能发送带附件的短信。"
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"OK"
                                                                         otherButtonTitles:nil, nil];
                                   [alert show];
                                   break;
                               }
                               else if(platformType == SSDKPlatformTypeMail && [error code] == 201)
                               {
                                   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                                   message:@"失败原因可能是：1、邮件应用没有设置帐号；2、设备不支持邮件应用；"
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"OK"
                                                                         otherButtonTitles:nil, nil];
                                   [alert show];
                                   break;
                               }
                               else
                               {
                                   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                                   message:[NSString stringWithFormat:@"%@",error]
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"OK"
                                                                         otherButtonTitles:nil, nil];
                                   [alert show];
                                   break;
                               }
                               break;
                           }
                           case SSDKResponseStateCancel:
                           {
                               [hud hide:YES];
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           default:
                               break;
                       }
                       
                       if (state != SSDKResponseStateBegin)
                       {
                           [hud hide:YES];
                           //[theController showLoadingView:NO];
                           //[theController.tableView reloadData];
                       }
                   }];
        
        //另附：设置跳过分享编辑页面，直接分享的平台。
        //        SSUIShareActionSheetController *sheet = [ShareSDK showShareActionSheet:view
        //                                                                         items:nil
        //                                                                   shareParams:shareParams
        //                                                           onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
        //                                                           }];
        //
        //        //删除和添加平台示例
        //        [sheet.directSharePlatforms removeObject:@(SSDKPlatformTypeWechat)];
        //        [sheet.directSharePlatforms addObject:@(SSDKPlatformTypeSinaWeibo)];
        
    }
}



@end
